package com.cavemanst.paint;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;

public class MainSurfaceView extends SurfaceView  implements SurfaceHolder.Callback, Runnable{

	private boolean m_is_running;
	private SurfaceHolder m_surfaceholder;
	private static int s_screen_width, s_screen_height;
	private Paint m_paint;
	private Thread m_mainthread;
	private float m_touch_x, m_touch_y, m_pen_size;
	private int m_paint_color;
	private Bitmap m_background_image;
	private Canvas m_offscreen_canvas;
	private Path m_draw_path;
	private static final float S_TOUCH_TOLERANCE = 4;
	
	public MainSurfaceView(Context context) {
		super(context);
		m_surfaceholder = getHolder();
		m_surfaceholder.addCallback(this);		
		setFocusable(true);
		s_screen_width = context.getResources().getDisplayMetrics().widthPixels;
		s_screen_height = context.getResources().getDisplayMetrics().heightPixels;		
	}

	private void Initialize(){
		
		m_pen_size = 5;
		m_touch_x = -1;
		m_touch_y = -1;
		m_paint_color = Color.BLACK;
		m_paint = new Paint(Paint.DITHER_FLAG);
		m_paint.setAntiAlias(true);
		m_paint.setDither(true);
		m_paint.setStyle(Paint.Style.STROKE);
		m_paint.setStrokeJoin(Paint.Join.ROUND);
		m_paint.setStrokeCap(Paint.Cap.ROUND);
        m_paint.setStrokeWidth(m_pen_size);
        m_paint.setColor(m_paint_color);
		m_draw_path = new Path();
		m_mainthread = new Thread(this);
		m_mainthread.start();
		m_is_running = true;
		
	}
	
	 @Override
     protected void onSizeChanged(int w, int h, int oldw, int oldh) {
         super.onSizeChanged(w, h, oldw, oldh);
         m_background_image = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888);
         m_offscreen_canvas = new Canvas(m_background_image);
     }
	
	private void Update(){
		
	}
	
	private void Draw(Canvas canvas){
		canvas.drawColor(Color.WHITE);
		canvas.drawBitmap(m_background_image, 0, 0, m_paint);
		canvas.drawPath(m_draw_path, m_paint);
	}
	
	@Override
	public boolean onTouchEvent(MotionEvent e){
		super.onTouchEvent(e);		
		float x = e.getX();
		float y = e.getY();
		if(e.getAction() == MotionEvent.ACTION_DOWN){			
			m_draw_path.reset();
			m_draw_path.moveTo(x, y);
			m_touch_x = x;
			m_touch_y = y;
		}else if(e.getAction() == MotionEvent.ACTION_MOVE){
			float dx = Math.abs(x - m_touch_x);
            float dy = Math.abs(y - m_touch_y);
            if (dx >= S_TOUCH_TOLERANCE || dy >= S_TOUCH_TOLERANCE) {
            	m_draw_path.quadTo(m_touch_x, m_touch_y, (x + m_touch_x)/2, (y + m_touch_y)/2);
                m_touch_x = x;
                m_touch_y = y;
            }			
		}else if(e.getAction() == MotionEvent.ACTION_UP){
			m_draw_path.lineTo(m_touch_x, m_touch_y);
			m_offscreen_canvas.drawPath(m_draw_path, m_paint);
			m_draw_path.reset();
		}
		return true;
	}

	@Override
	public void run() {
		while(m_is_running){
			try{
				// Thread.sleep(20);
			}catch(Exception e){}
			Update();
			Canvas m_lockcanvas = m_surfaceholder.lockCanvas(null);
			synchronized (m_surfaceholder) {
				if(m_lockcanvas != null){
					Draw(m_lockcanvas);
					m_surfaceholder.unlockCanvasAndPost(m_lockcanvas);
				}
			}
		}		
	}
	
	public void Reset_Canvas(){
		m_offscreen_canvas.drawColor(Color.WHITE);
		m_draw_path.reset();
		m_touch_x = -1;
		m_touch_y = -1;
		m_pen_size = 5;
		m_paint_color = Color.BLACK;
		m_paint.setAntiAlias(true);
		m_paint.setDither(true);
		m_paint.setStyle(Paint.Style.STROKE);
		m_paint.setStrokeJoin(Paint.Join.ROUND);
		m_paint.setStrokeCap(Paint.Cap.ROUND);
        m_paint.setStrokeWidth(m_pen_size);
        m_paint.setColor(m_paint_color);
	}

	@Override
	public void surfaceChanged(SurfaceHolder arg0, int arg1, int arg2, int arg3) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void surfaceCreated(SurfaceHolder arg0) {
		Initialize();
		
	}

	@Override
	public void surfaceDestroyed(SurfaceHolder arg0) {
		boolean retry = true;
		m_is_running = false;
        do {
            try {
                m_mainthread.join();
                retry = false;
            } catch (InterruptedException e) {
				e.printStackTrace();
                // we will try it again and again...
            }
        }while(retry);
		
	}

}
